import {
	enterBig,
	createWS
} from '@/api/index.js'
import {
	messageBody,
	wsSend
} from '../../utils/index.js'
import {
	Ws
} from './model.js'
export default {
	data() {
		return {
			bigId: '',
			meetingId: '',
			waiterId: '',
			bigSocketTask: {},
			socketTask: {},
			bigwsOpen: false,
			wsOpen: false,
			timeout: 4000,
			interval: 8000,
			clientTimer: null,
			severTimer: null,
			chatTimer: null,
			keepTime: 180000,
			smartTalkerType: '',
			smartTalkerId: '',
			bigTalkerType: '',
			bigTalkerId: '',
			waiterId: '',
			waiterType: '',
			reconnectNum: 0,
			reconnectLimit: 5,
			serviceInter: false, //客服接入
			reconcatToast: false,
			queueNum:null //进入大会场等待人数
		}
	},
	filters: {
		timestamp(val) {
			return new Date(val).toLocaleTimeString()
		}
	},
	watch: {
		wsOpen: { //监听小会场建立成功
			handler(newVal) {
				if (newVal) {
					this.socketTask.onMessage((e) => {
						this.onMessage(e)
					})
				}
			}
		},
		reconnectNum(val) {
			if (val === 0 ) {
				uni.hideLoading();
			}else{
				uni.showLoading({
					title: '重连中'
				});
			}
		},
	},
	methods: {
		/*创建大会场*/
		creatBigMeeting() {
			uni.showLoading({
				title: '连接中'
			});
			let token = window.sessionStorage.getItem('token') || ''
			let ticket = window.sessionStorage.getItem('ticket') || ''
			let IM_UUID = ''
			let type = 4
			if (ticket) {
				type = 2
			} else if (!ticket && !token) {
				type = 4
			} else {
				type = 3
			}
			if (type === 4) {
				IM_UUID = window.localStorage.getItem('IM_UUID') || ''
			}
			const params = {
				type,
				token,
				ticket,
				IM_UUID
			}
			enterBig(params).then((res) => {
				const {
					data
				} = res
				this.bigId = data.mainId
				this.bigTalkerType = data.userType
				this.bigTalkerId = data.token
				this.ID = data.token
				if (data.userType == '4') {
					window.localStorage.setItem('IM_UUID', data.token)
				}
				uni.hideLoading()
				if (this.bigId) {
					this.createWebsocket()
				} else {
					uni.showToast({
						title: '大会场接入失败',
						duration: 2000,
						icon: 'none'
					});
				}
			}).catch(err => {
				uni.hideLoading()
				uni.showToast({
					title: '大会场接口异常！',
					duration: 2000,
					icon: 'none'
				});
				throw new Error(`获取大会场信息接口异常${err}`)
			})
		},
		// ws连接
		async createWebsocket() {
			const params = `?talkerType=${this.bigTalkerType}&talkerId=${this.bigTalkerId}&meetingId=${this.bigId}`
			this.bigSocketTask = await createWS(params)
			this.wsListener()
		},
		// ws监听
		wsListener() {
			this.bigSocketTask.onOpen(() => {
				this.bigwsOpen = true
				this.reconnectNum = 0
				this.heartStart()
				console.log('大会场连接上了')
			})
			this.bigSocketTask.onMessage((e) => {
				this.heartStart()
				let {
					data
				} = e
				const message = JSON.parse(data)
				// 正常消息
				let base = {
					id: message.serial,
					time: message.sTime,
				}
				let params = {}
				if (message.type === '0x20') { //主会场欢迎辞
					this.smartTalkerType = message.content.talkerType
					this.smartTalkerId = message.content.talkerId
					this.ID = this.smartTalkerId
				}
				if (message.type === '0x66' || message.type === '0x61') { //自动分配    
					if (this.socketTask && this.socketTask.wsOpen) { //先断开原来连接
						this.socketTask.close()
					}
					this.meetingId = message.content.smallMeetingId
					this.waiterId = message.content.waiterId
					this.waiterType = message.content.waiterType
					const s =
						`?talkerType=${this.smartTalkerType}&talkerId=${this.smartTalkerId}&meetingId=${this.meetingId}&otherId=${this.waiterId}`
					const wsInstance = new Ws(s)
					wsInstance.createWebsocket()
					this.socketTask = wsInstance.socketTask
					this.socketTask.onOpen(() => {
						this.wsOpen = true
						console.log('小会场连接上了')
					})
					this.socketTask.onClose(() => {
						this.wsOpen = false
						console.log('小会场关闭了')
					})
				}
				if(message.type === '0x72'){
					this.queueNum = Number(message.content)
				}
		        if( message.type === '0x69'||message.type === '0x71'|| message.type === '0x73' || message.type === '0x74'){
					params = {
						type: 'user',
						uid: 'message.content.talkerId',
						content: {
							text: message.content
						},
						talkType: 'text'
					}
				}
				let	showData = messageBody({ ...base,
								...params
							})
				this.screenMsg(showData);
			})
			this.bigSocketTask.onClose(() => {
				console.log('大会场关闭了')
			})
		},
		heartStart() {
			this.serverTimer && clearTimeout(this.serverTimer);
			this.clientTimer && clearInterval(this.clientTimer);
			this.clientTimer = setInterval(() => {
				//发送消息，服务端返回信息，即表示连接良好，可以在socket的onmessage事件重置心跳机制函数
				let params = {
					contentType: '0x25',
					content: ''
				}
				wsSend(this.bigSocketTask, params)
				//定义一个延时器等待服务器响应，若超时，则关闭连接，重新请求server建立socket连接
				this.serverTimer && clearTimeout(this.serverTimer);
				this.serverTimer = setTimeout(() => {
					this.bigSocketTask.close();
					this.reConnect();
				}, this.timeout);
			}, this.interval);
		},
		reConnect() {
			this.chatTimer && clearTimeout(this.chatTimer) //重连操作时清楚静待超时计时器
			if (this.reconnectNum >= this.reconnectLimit) {
				this.clearTimer()
				this.reconnectNum = 0;
				uni.showModal({
					title: '提示',
					showCancel: false,
					content: '连接失败，请退出重试',
					success: function() {
						window.location.reload()
					}
				});
				return;
			}
			this.reconnectNum++;
			this.createWebsocket()
		},
		onMessage(e) {
			this.meetingTimeout()
			let {
				data
			} = e
			const message = JSON.parse(data)
			// 正常消息
			let base = {
				id: message.serial,
				time: message.sTime,
			}
			let params = {}
			if (message.type === '0x27') {
				this.editTitle(0)
			}
			if (message.type === '0x28') {
				this.editTitle(1)
			}
			if (message.type === '0x30' || message.type === '0x31') { //欢迎、告别辞
				params = {
					type: 'system',
					uid: '9527_',
					content: {
						text: message.content.word
					},
					talkType: 'text'
				}
			}
			if (message.type === '0x26') {
				this.socketTask.close()
				this.bigSocketTask.close()
				this.clearTimer()
				uni.showModal({
					title: '提示',
					showCancel: false,
					content: '您长时间未响应，连接暂时断开.',
					success: function() {
						window.location.reload()
					}
				});
			}
			if (message.type === '0x32') {
				params = {
					type: 'user',
					uid: '9527_',
					content: {
						text: '尊敬的用户，很高兴为您服务，请问有什么可以帮到您？'
					},
					talkType: 'text'
				}
				this.serviceInter = true
			}
			if (message.type === '0x65' || message.type === '0x34') { //客服关闭窗口
				this.socketTask.close()
				this.bigSocketTask.close()
				this.clearTimer()
				uni.showModal({
					title: '提示',
					showCancel: false,
					content: '客服结束了会话, 希望再次为您服务!',
					success: function() {
						window.location.reload()
					}
				});
			}
			if (message.type === '0x41') { //文字对话且不是自己说的话
				params = {
					type: 'user',
					uid: message.content.talkerId,
					content: {
						text: message.content.word
					},
					talkType: 'text'
				}
			}
			if (message.type === '0x45') { //图片对话且不是自己说的话
				params = {
					type: 'user',
					uid: message.content.talkerId,
					content: {
						url: message.content.word
					},
					talkType: 'img'
				}
			}
			if (message.type === '0x62') { // 发送工具连接
				params = {
					type: 'link',
					uid: message.content.talkerId,
					content: {
						link: JSON.parse(message.content.word)
					},
					talkType: 'link'
				}
			}
		   let	showData = messageBody({ ...base,
				...params
			})
			this.screenMsg(showData);
		},
		// 计时关闭小会场（静待超时）
		meetingTimeout() {
			this.chatTimer && clearTimeout(this.chatTimer)
			this.chatTimer = setTimeout(() => {
				let params = {
					contentType: '0x26',
					content: '用户静待超时'
				}
				wsSend(this.socketTask, params)
				// this.$nextTick(() => {
				// 	this.socketTask.close()
				// 	this.bigSocketTask.close()
				// })
				// this.clearTimer()
				// // this.$refs.popup.open()
				// uni.showModal({
				// 	title: '提示',
				// 	showCancel: false,
				// 	content: '由于您长时间未响应，连接暂时断开.',
				// 	success: function() {
				// 		window.location.reload()
				// 	}
				// });
			}, this.keepTime)
		},
		// 更改标题
		editTitle(event) {
			if (event == 0) {
				uni.setNavigationBarTitle({
					title: '对方正在输入...'
				})
			} else {
				uni.setNavigationBarTitle({
					title: '客服咨询'
				})
			}
		},
		clearTimer() {
			this.clientTimer && clearInterval(this.clientTimer);
			this.serverTimer && clearTimeout(this.serverTimer);
			this.chatTimer && clearTimeout(this.chatTimer)
		}
	},
}
